package com.fyzk.activity.chongzhi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.fyzk.activity.main.MainGroupActivityI;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.UserInfoResponse;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.fyzk.utils.LogUtils;
import com.fyzk.view.TopTitleView;
import com.tyjc.lottery.R;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

/**
 * 充值界面(h5)
 */
@ContentView(R.layout.ac_recharge_new)
public class RechargeNewActivity extends BaseActivity implements onTopTitleClickListener {
    @ViewInject(R.id.topview)
    private TopTitleView topTitleView;

    @ViewInject(R.id.recharge_webview)
    private WebView webView;

    @ViewInject(R.id.recharge_progress)
    private ProgressBar progressBar;

    private String url = "";
    private String money = "";
    private String title = "";

    private UserInfoResponse userInfoResponse;

    private String orderId = "";    // 投注订单号
    private long lowMoney = 0;       // 投注差额

    private String firstUrl = "";
    private String nowUrl = "";

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        url = getIntent().getStringExtra("url");
        money = getIntent().getStringExtra("money");
        title = getIntent().getStringExtra("title");

        topTitleView.setOnTitleClickListener(this);
        topTitleView.setCenterText(title);

        webView.setBackgroundColor(Color.WHITE);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置setWebChromeClient对象
        webView.setWebViewClient(new MyWebViewClient());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    if (progressBar.getVisibility() == View.GONE)
                        progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        webView.addJavascriptInterface(new JavaScriptInterface(this), "android");

        String recharge_url = url;
        if ("H5支付".equals(title)) {
            recharge_url = url + "&tk=" + MySharedPreferences.getInstance().getAuthtoken() + "&app=app" + "&money=" + money;
        }
        firstUrl = recharge_url;
        webView.loadUrl(recharge_url);

        // 浏览器打开
//        LogUtil.v(recharge_url);
//        Uri uri = Uri.parse(""+recharge_url);
//        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//        startActivity(intent);
//        finish();
    }

    public void payresult() {
        Intent intent = new Intent(RechargeNewActivity.this, MainGroupActivityI.class);
        MySharedPreferences.getInstance().setOpenStatus(true);
        startActivity(intent);
        finish();
    }

    private class MyWebViewClient extends WebViewClient {

        // 在WebView中而不是默认浏览器中显示页面
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            nowUrl = url;
            LogUtils.e("====访问的url地址====" + url);
            if (parseScheme(url)) {
                try {
                    Uri uri = Uri.parse(url);
                    Intent intent;
                    intent = Intent.parseUri(url,
                            Intent.URI_INTENT_SCHEME);
                    intent.addCategory("android.intent.category.BROWSABLE");
                    intent.setComponent(null);
                    // intent.setSelector(null);
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    new AlertDialog.Builder(getContext())
                            .setMessage("未检测到支付宝客户端，请安装后重试。")
                            .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                    startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                }
                            }).setNegativeButton("取消", null).show();
                }
            } else {
                if (url.startsWith("weixin://wap/pay?")) {
                    //如果return false  就会先提示找不到页面，然后跳转微信
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return false;
            }


            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, android.net.http.SslError error) { // 重写此方法可以让webview处理https请求
            handler.proceed();
        }
    }

    public boolean parseScheme(String url) {

        if (url.contains("platformapi/startapp")
                || url.contains("alipays://platformapi")
                || url.contains("platformapi/startApp")) {

            return true;
        } else {

            return false;
        }
    }

    public boolean shouldOverrideUrlLoading(final WebView view, String url) {
        // 获取上下文, H5PayDemoActivity为当前页面
        final Activity context = this;

        // ------  对alipays:相关的scheme处理 -------
        if (url.startsWith("alipays:") || url.startsWith("alipay")) {
            try {
                context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
            } catch (Exception e) {
                new AlertDialog.Builder(context)
                        .setMessage("未检测到支付宝客户端，请安装后重试。")
                        .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                context.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                            }
                        }).setNegativeButton("取消", null).show();
            }
            return true;
        }
        // ------- 处理结束 -------

        if (!(url.startsWith("http") || url.startsWith("https"))) {
            return true;
        }

//        view.loadUrl(url);
        return true;
    }

    @JavascriptInterface
    public void rechargeBack() {
        finish();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            if (nowUrl.equals(firstUrl)) {
                finish();
            } else {
                webView.goBack();// 返回前一个页面
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
